import os, sys, time, platform
from loguru import logger
from . import synlicense

# os.path.abspath: 获取完整路径(包含文件名)
current_exec_abspath = os.path.abspath(__file__)
current_exec_dir_name, _ = os.path.split(current_exec_abspath)
current_up_dir, _ = os.path.split(current_exec_dir_name)
current_up2_dir, _ = os.path.split(current_up_dir)
current_up3_dir, _ = os.path.split(current_up2_dir)

plat = platform.system().lower()

# 日志文件路径设置
log_dir_docker = '../'
log_path = f"{log_dir_docker}diningpos_logs"
image_path = f"{current_up3_dir}/diningpos_image"
soft_path = f"{current_up3_dir}/diningpos_soft"

if not os.path.exists(log_path):
    os.makedirs(log_path)

if not os.path.exists(image_path):
    os.makedirs(image_path)

if not os.path.exists(soft_path):
    os.makedirs(soft_path)

t = time.strftime("%Y_%m_%d")
log_path_file = f"{log_path}/interface_log_{t}.log"
'''
# 兼容别的logger, 完全整合logging的工作方式
# 将所有的logging都用loguru的logger再发送一遍消息
# class InterceptHandler(logging.Handler):
#     def emit(self, record):
#         logger_opt = logger.opt(depth=6, exception=record.exc_info)
#         logger_opt.log(record.levelname, record.getMessage())
# 初始化 loguru 配置
'''


def setup_logging():
    # logging.basicConfig(handlers=[InterceptHandler(level='INFO')], level='INFO', encoding="utf-8")
    # logger.configure(handlers=[{"sink": sys.stderr, "level": 'INFO'}])  # 配置日志到标准输出流
    logger.add(
        log_path_file,
        # Automatically rotate too big file
        # for example: "10 MB"、"0.5 GB"、"1 month 2 weeks"、"4 days"、"10h"、"18:00"...
        rotation="10 MB",
        # Cleanup after some time
        # for example: "10 days"、"1 week, 3 days"、"2 months"、"1 minutes"...
        retention="90 days",
        encoding="utf-8",
        # Asynchronous, Thread-safe, Multiprocess-safe
        enqueue=True,
        level="INFO",
        # backtrace=True,
        # diagnose=True,
        # Save some loved space
        # for example: "gz", "bz2", "xz", "lzma", "tar", "tar.gz", "tar.bz2", "tar.xz", "zip".
        compression="tar.gz")


setup_logging()

logger.info('server start...')

diningLimit = 1
stallLimit = 1
dishesLimit = 10
'''
license_file_path = f'{current_up2_dir}/diningpos_licensees'
try:
    license_info = synlicense.get_licensees_info(license_file_path)
    if license_info is False:
        msg = f'授权文件{license_file_path}内容为空, 服务退出...'
        logger.error(msg)
        print('synlog=', msg)
        sys.exit(0)

    license_mac = synlicense.get_pre_license()
    if len(license_mac) <= 0 or license_mac != license_info.get('hardware_info'):
        msg = f'设备授权码不匹配, 服务退出...'
        logger.error(msg)
        print('synlog=', msg)
        sys.exit(0)

    logger.info('设备授权成功')
    diningLimit = license_info['diningLimit']
    stallLimit = license_info['stallLimit']
    dishesLimit = license_info['dishesLimit']
except FileNotFoundError:
    msg = f'授权文件{license_file_path}不存在, 服务退出...'
    logger.error(msg)
    print('synlog=', msg)
    sys.exit(0)
except PermissionError:
    msg = f'授权文件{license_file_path}存在但没有权限访问, 服务退出...'
    logger.error(msg)
    print('synlog=', msg)
    sys.exit(0)
except Exception as e:
    msg = f'授权文件{license_file_path}异常{str(e)}, 服务退出...'
    logger.error(msg)
    print('synlog=', msg)
    sys.exit(0)
'''

jwtToenKey = 'synjones1234567890'
signatureKey = 'synjones1234567890'

DB_Host = os.environ.get("DP_Mongo_Host")
DB_Port = os.environ.get("DP_Mongo_Port")
DB_UserName = os.environ.get("DP_Mongo_UserName")
DB_Password = os.environ.get("DP_Mongo_Password")

if DB_Host is None or \
    DB_Port is None or \
    DB_UserName is None or \
    DB_Password is None:

    if DB_Password is None:
        DB_Password_len = 0
    else:
        DB_Password_len = len(DB_Password)

    logger.error(f'需要配置MongoDB环境变量:'
                 f'DB_Host={DB_Host},'
                 f'DB_Port={DB_Port},'
                 f'DB_UserName={DB_UserName},'
                 f'DB_Password len={DB_Password_len}')

    sys.exit(0)

database = {
    "host": DB_Host,
    "port": int(DB_Port),
    "username": DB_UserName,
    "password": DB_Password
}

super_administrator = '超级管理员'
'''
系统权限列表, 除了超级管理员外，其他角色不能创建角色和权限
    endpoint: Blueprint('xxx').route
    'xx': ['xxx', ...]
'''
all_permission_key = [
    "super_server", "super_dining", "super_stall", "super_user", "super_role",
    "dining", "stall", "device", "dish_manage", "dish_check", "order_stats"
]

all_permission = {
    "super_server": {
        "name": "学校信息",
        "desc": "修改学校信息...",
        "power": ["server_manage", "server_query"]
    },
    "super_dining": {
        "name": "餐厅管理",
        "desc": "管理餐厅创建、删除、编辑...",
        "power": ["dining_manage", "dining_query"]
    },
    "super_stall": {
        "name": "档口管理",
        "desc": "创建档口、修改档口信息...",
        "power": ["stall_manage", "stall_query"]
    },
    "super_user": {
        "name": "用户管理",
        "desc": "开通账户信息...",
        "power": ["user_manage", "user_query"]
    },
    "super_role": {
        "name": "角色管理",
        "desc": "定义角色权限...",
        "power": ["user_role", "user_rolePower"]
    },
    "dining": {
        "name": "餐厅管理",
        "desc": "管理餐厅创建、删除、编辑...",
        "power": ["dining_manage", "dining_query"]
    },
    "stall": {
        "name": "档口管理",
        "desc": "创建档口、修改档口信息...",
        "power": ["dining_query", "stall_manage", "stall_query"]
    },
    "device": {
        "name": "设备管理",
        "desc": "查看硬件状态、发布软件版本...",
        "power": ["pos_manage", "upgrade_manage"]
    },
    "dish_manage": {
        "name": "菜品管理",
        "desc": "录入菜品信息、编辑菜品、删除菜品、提交菜品上架申请...",
        "power": ["dish_manage", "dish_query"]
    },
    "dish_check": {
        "name": "菜品审批",
        "desc": "审批菜品",
        "power": ["dish_check"]
    },
    "order_stats": {
        "name": "查看报表",
        "desc": "档口餐次汇总、菜品消费分析、档口消费明细...",
        "power":
        ["order_manage", "order_query", "stats_manage", "stats_query"]
    }
}

export_permission = {
    "dining": {
        "name": "餐厅管理",
        "desc": "管理餐厅创建、删除、编辑...",
        "power": ["dining_manage", "dining_query"]
    },
    "stall": {
        "name": "档口管理",
        "desc": "创建档口、修改档口信息...",
        "power": ["dining_query", "stall_manage", "stall_query"]
    },
    "device": {
        "name": "设备管理",
        "desc": "查看硬件状态、发布软件版本...",
        "power": ["pos_manage", "upgrade_manage"]
    },
    "dish_manage": {
        "name": "菜品管理",
        "desc": "录入菜品信息、编辑菜品、删除菜品、提交菜品上架申请...",
        "power": ["dish_manage", "dish_query"]
    },
    "dish_check": {
        "name": "菜品审批",
        "desc": "审批菜品",
        "power": ["dish_check"]
    },
    "order_stats": {
        "name": "查看报表",
        "desc": "档口餐次汇总、菜品消费分析、档口消费明细...",
        "power":
        ["order_manage", "order_query", "stats_manage", "stats_query"]
    }
}